//
//  PPBluetoothMonitor.m
//  PetParadise
//
//  Created by Frank on 9/5/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#define kServiceUUID @"FFF0"
#define kDeviceName @"iChaser"

#import "PPBluetoothMonitor.h"
@import AudioToolbox;
@import CoreBluetooth;
@import QuartzCore;
#import "UIAlertView+Blocks.h"

@interface PPBluetoothMonitor() <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) NSMutableArray *deviceArray;
@property (nonatomic, strong) NSArray *pairedDeviceArray;
@property (nonatomic, strong) NSMutableArray *toConnectDeviceArray;
@property (nonatomic, strong) NSMutableArray *connectedDeviceArray;
@property (nonatomic) SystemSoundID mySound;

@end

@implementation PPBluetoothMonitor

- (id)initWithIdentifiers:(NSArray *)identifiers
{
    self = [super init];
    if (self) {
        self.pairedDeviceArray = identifiers;
    }
    self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
    //[self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:nil];
    self.toConnectDeviceArray = [NSMutableArray array];
    return self;
}

#pragma mark - Blue Tooth Delegate

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    NSLog(@"------>1");
    NSString *deviceName = advertisementData[CBAdvertisementDataLocalNameKey];
//    NSArray *serviceUUIDs = advertisementData[CBAdvertisementDataServiceUUIDsKey];
    if ([deviceName isEqual:kDeviceName]) {
        NSString *UUIDString = peripheral.identifier.UUIDString;
        BOOL alreadyExist = NO;
        for (NSString *string in self.pairedDeviceArray) {
            if ([string isEqual:UUIDString]) {
                alreadyExist = YES;
            }
        }
        if (alreadyExist) {
            [self.toConnectDeviceArray addObject:peripheral];
            [self.centralManager connectPeripheral:peripheral options:nil];
        }
    }
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    switch (central.state) {
        case CBCentralManagerStatePoweredOn:
            NSLog(@"CentralManagerState PoweredOn");
            [self.centralManager scanForPeripheralsWithServices:nil options:nil];
            break;
        case CBCentralManagerStateUnknown :
            NSLog(@"CentralManagerState Unknown");
            break;
        case CBCentralManagerStateResetting :
            NSLog(@"CentralManagerState Resetting");
            break;
        case CBCentralManagerStateUnsupported :
            NSLog(@"CentralManagerState Unsupported");
            [UIAlertView showWithTitle:@"此设备硬件不支持" message:@"宠物防走失智能在支持蓝牙4.0的设备上使用" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
            
            break;
        case CBCentralManagerStatePoweredOff :
            [UIAlertView showWithTitle:@"蓝牙未打开" message:@"请开启设备蓝牙，以使用宠物防走失功能" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
            break;
        default:
            NSLog(@"Central Manager did change state");
            break;
            
    }
    
}


- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral
{
    NSLog(@"------>2");
    peripheral.delegate = self;
    [peripheral discoverServices:nil];
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
        NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"out" ofType:@"caf"];
        NSURL *soundURL = [NSURL fileURLWithPath:soundPath];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)soundURL, &_mySound);
        AudioServicesPlaySystemSound(self.mySound);
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    NSLog(@"------>3");
    CBPeripheral *myPeriperal = peripheral;
    NSArray *services = myPeriperal.services;
    for (CBService *service in myPeriperal.services) {
        NSLog(@"%@", service.UUID);
        if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]]) {
            //            for (CBCharacteristic *characteristic in service.characteristics) {
            //                NSLog(@"%@", characteristic);
            //            }
            [peripheral discoverCharacteristics:nil forService:service];
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    NSLog(@"------>4");
    for (CBCharacteristic *characteristic in service.characteristics) {
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF2"]]) {
            NSString *string = @"01";
            NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
            [peripheral writeValue:data forCharacteristic:characteristic type:CBCharacteristicWriteWithResponse];
        }
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didWriteValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    NSLog(@"------>5");
    if (error) {
        NSLog(@"failed");
    } else {
        NSLog(@"write success");
        [UIAlertView showWithTitle:@"狗牌链接成功" message:@"现在设定的距离是30米" cancelButtonTitle:@"确定" otherButtonTitles:nil tapBlock:nil];
    }
}

- (void)beginMonitoring
{
    [self.centralManager scanForPeripheralsWithServices:@[[CBUUID UUIDWithString:@"FFF0"]] options:nil];
}

- (void)stopMonitoring
{
    [self.centralManager stopScan];
}

- (void)disConnectAll
{
    NSArray *deviceArray = [self.centralManager retrieveConnectedPeripheralsWithServices:nil];
    for (CBPeripheral *peripheral in deviceArray) {
        [self.centralManager cancelPeripheralConnection:peripheral];
    }
}


@end
